# Get started with a build env with Rust nightly
FROM rustlang/rust:nightly AS builder

# Use USTC mirrors for APT to speed up download
RUN if [ -f /etc/apt/sources.list.d/debian.sources ]; then \
        sed -i 's/deb.debian.org/mirrors.ustc.edu.cn/g' /etc/apt/sources.list.d/debian.sources; \
    else \
        sed -i 's/deb.debian.org/mirrors.ustc.edu.cn/g' /etc/apt/sources.list && \
        sed -i 's/security.debian.org/mirrors.ustc.edu.cn/g' /etc/apt/sources.list; \
    fi

# Install Node.js, npm, and binaryen (for wasm-opt)
# rustlang/rust is based on Debian, so we use apt-get
RUN apt-get update && \
    apt-get install -y nodejs npm binaryen && \
    rm -rf /var/lib/apt/lists/*

RUN npm config set registry https://registry.npmmirror.com && \
    npm install -g sass

# RUN apk add curl

ENV RUSTUP_UPDATE_ROOT=https://mirrors.ustc.edu.cn/rust-static/rustup
ENV RUSTUP_DIST_SERVER=https://mirrors.ustc.edu.cn/rust-static

# Install Rust toolchain (nightly) via rustup
# RUN curl https://sh.rustup.rs -sSf | sh -s -- -y --default-toolchain nightly
# RUN apk add --no-cache rustup && \
#     rustup-init -y --default-toolchain nightly --profile minimal
# ENV PATH="/root/.cargo/bin:${PATH}"

# 配置 Cargo 镜像源
RUN mkdir -p /root/.cargo && \
    echo '[source.crates-io]' > /root/.cargo/config.toml && \
    echo 'replace-with = "ustc"' >> /root/.cargo/config.toml && \
    echo '[source.ustc]' >> /root/.cargo/config.toml && \
    echo 'registry = "sparse+https://mirrors.ustc.edu.cn/crates.io-index/"' >> /root/.cargo/config.toml

RUN cargo install crm 

RUN crm best sparse

RUN cargo install cargo-binstall

# Install cargo-leptos via crates.io (avoids GitHub release download)
RUN cargo binstall cargo-leptos

# Pre-install wasm-bindgen CLI to match crate version (0.2.106)
RUN cargo install -f wasm-bindgen-cli --version 0.2.106 --locked

# Add the WASM target
RUN rustup target add wasm32-unknown-unknown

WORKDIR /work
COPY package.json package-lock.json ./
RUN npm install
COPY . .

RUN cargo leptos build --release

FROM rustlang/rust:nightly-slim AS runner

WORKDIR /app

COPY --from=builder /work/target/release/server /app/
COPY --from=builder /work/target/site /app/site
COPY --from=builder /work/Cargo.toml /app/

ENV RUST_LOG="info"
ENV LEPTOS_SITE_ADDR="0.0.0.0:8080"
ENV LEPTOS_SITE_ROOT=./site
EXPOSE 8080

CMD ["/app/server"]
